import React, { memo, useEffect, useState, useCallback } from "react";

import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Pagination,
  Popconfirm,
} from "antd";
import { UserOutlined } from "@ant-design/icons";
import { Useradminwrap } from "./style";
import request from "@/service/request";
import Uploadyzh from "@/components/uploadyzh";
import qs from "qs";

const { Column } = Table;

export default memo(function Useradmin() {
  //存储用户信息
  const [userlist, setUserlist] = useState([]);
  //方便搜索的用户信息
  const [userlist1, setUserlist1] = useState([]);
  //对话框是否显示
  const [isModalVisible, setIsModalVisible] = useState(false);
  //用户id
  const [uid, setUid] = useState();
  //用户头像
  const [imguser, setImguser] = useState("");
  //用来清空表单
  const [form1] = Form.useForm();
  //每一页的数量
  const [pagesize, setPagesize] = useState(5);
  //当前在第几页
  const [currentindex, setCurrentindex] = useState(0);
  //获取所用用户信息
  useEffect(() => {
    request.get("travel/ALLusers").then((res) => {
      setUserlist(res);
      setUserlist1(res);
    });
  }, []);
  //打开修改用户信息表单
  const xiugai = (message) => {
    setIsModalVisible(true);
    form1.setFieldsValue(message);
    setImguser(message.aventer);
    setUid(message.id);
  };
  //提交修改用户信息的表单
  const onFinish = (values) => {
    values.aventer = imguser;
    values.id = uid;
    request.post("travel/handleuser", qs.stringify(values)).then((value) => {
      message.success("修改信息成功");
      setIsModalVisible(false);
      request.get("travel/ALLusers").then((res) => {
        setUserlist(res);
        setUserlist1(res);
      });
    });
  };
  //传回来的用户头像
  const setimg = useCallback((img) => {
    setImguser(img);
  }, []);
  //取消对话框
  const cancel = () => {
    form1.resetFields();
    setImguser("");
  };
  //分页改变
  const pagechange = useCallback((page, size) => {
    setPagesize(size);
    setCurrentindex((page - 1) * size);
  }, []);
  //删除用户
  const deleteuser = useCallback((text) => {
    request.get(`travel/handleuser?id=${text.id}`).then((value) => {
      message.success("删除用户成功");
      request.get("travel/ALLusers").then((res) => {
        setUserlist(res);
        setUserlist1(res);
      });
    });
  }, []);
  //搜索用户输入框变化时
  const searchchange = useCallback(
    (e) => {
      setUserlist(
        userlist1.filter((item) => {
          return item.username.indexOf(e.target.value) !== -1;
        })
      );
    },
    [userlist1]
  );
  return (
    <Useradminwrap>
      <div className="top">你当前的位置>用户管理</div>
      <Input
        size="large"
        placeholder="输入你要搜索的用户名"
        onChange={searchchange}
        prefix={<UserOutlined />}
      />
      {/* 修改用户信息对话框 */}
      <Modal
        title="修改用户信息"
        visible={isModalVisible}
        onCancel={(e) => setIsModalVisible(false)}
        footer={[]}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          // initialValues={imguser}
          onFinish={onFinish}
          form={form1}
          autoComplete="off"
          onCancel={cancel}
        >
          <Form.Item
            label="用户名"
            name="userName"
            rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "Please input your password!" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            label="昵称"
            name="nickName"
            rules={[{ required: true, message: "Please input your userNick!" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="aventer"
            label="头像"
            rules={[
              {
                required: true,
                message: "Please input Intro",
              },
            ]}
          >
            <div className="upload">
              <Uploadyzh setimg={setimg} imgurl={imguser}></Uploadyzh>
            </div>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              修改用户信息
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Table
        dataSource={userlist.slice(currentindex, currentindex + pagesize)}
        scroll={{ y: 400 }}
        rowKey={(r) => r.id}
        pagination={false}
      >
        <Column title="用户名" dataIndex="userName" key="userName" />
        <Column title="密码" dataIndex="password" key="password" />
        <Column title="昵称" dataIndex="nickName" key="nickName" />
        <Column
          title="头像"
          key="aventer"
          render={(text) => {
            return (
              <img
                src={text.aventer}
                alt=""
                style={{ width: 60, height: 40 }}
              ></img>
            );
          }}
        />
        <Column
          title="操作"
          key="caozuo"
          render={(text) => (
            <div>
              <Button
                type="primary"
                shape="round"
                size={"middle"}
                onClick={(e) => xiugai(text)}
              >
                修改
              </Button>
              <Popconfirm
                title="你确定删除此用户吗？"
                okText="确定"
                cancelText="取消"
                onConfirm={(e) => deleteuser(text)}
              >
                <Button type="primary" danger shape="round" size={"middle"}>
                  删除
                </Button>
              </Popconfirm>
            </div>
          )}
        />
      </Table>
      <div className="page">
        <Pagination
          pageSize={pagesize}
          total={userlist.length}
          onChange={pagechange}
          showSizeChanger
          pageSizeOptions={[5, 8, 10]}
        />
      </div>
    </Useradminwrap>
  );
});
